$(function() {
	 
	// 验证
	validateInit();

	$('#contractTable').bootstrapTable({
		data : getDatas(),
		striped : true,
		cache : false,
		pagination : true,
		sortable : false,
		toolbar : "#contractToolbar",
		sidePagination : "client",
		pageNumber : 1,
		pageSize : 10,
		pageList : [ 10, 25, 50, 100 ],
		search : true,
		strictSearch : false,
		showColumns : true,
		clickToSelect : true,
		uniqueId : 'id',
		columns : [ {
			checkbox : true,
		}, {
			field : 'customerName',
			title : '客户姓名'
		}, {
			field : 'deviceName',
			title : '设备名称'
		}, {
			field : 'startTime',
			title : '保修起始时间',
			formatter : function(value, row, index) {
				return moment(value).format('YYYY-MM-DD');
			}
		}, {
			field : 'endTime',
			title : '保修截止时间',
			formatter : function(value, row, index) {
				return moment(value).format('YYYY-MM-DD');
			}
		},{
			field : 'operate',
			title : '操作'
		}],
		onDblClickRow : function(row) {// 双击查看详情
			showContractDetail(row);
		}
	});

	$("#contractTable").bootstrapTable("hideColumn", "id");
});


//bsSuggest
var isBsSuggestCustomerIdSelected = false;
var isBsSuggestDeviceIdSelected = false;
function validateInit() {
	
	$.validator.addMethod("isBsSuggestCustomerIdSelected", function(value, element) { 
    	return isBsSuggestCustomerIdSelected;       
	}, "必须选择给定的客户姓名"); 
	$.validator.addMethod("isBsSuggestDeviceIdSelected", function(value, element) { 
		return isBsSuggestDeviceIdSelected;       
	}, "必须选择给定的设备名称");
	
	
	$.validator.addMethod("isDate", function(value, element) { 
		return isDate(value);
	}, "输入的日期不合法"); 
	$.validator.addMethod("isEndDateGreaterThanStartDate", function(value, element) { 
		var startDate = $("#addContractForm [name='startTime']").val();
		var endDate = $("#addContractForm [name='endTime']").val();
		return isEndDateGreaterThanStartDate(startDate, endDate);
	}, "保修结束日期不得早于开始日期"); 
	
	$.validator.addMethod("isUpdateEndDateGreaterThanStartDate", function(value, element) { 
		var startDate = $("#updateContractForm [name='startTime']").val();
		var endDate = $("#updateContractForm [name='endTime']").val();
		return isEndDateGreaterThanStartDate(startDate, endDate);
	}, "保修结束日期不得早于开始日期"); 

	$("#addContractForm").validate({
		rules : {
			suggestCustomerId : {
				required : true,
				isBsSuggestCustomerIdSelected: true
			},
			suggestDeviceId : {
				required : true,
				isBsSuggestDeviceIdSelected: true
			},
			startTime: {
				required: true,
				isDate: true
			},
			endTime: {
				required: true,
				isDate: true,
				isEndDateGreaterThanStartDate: true
			}
		},
		messages : {
			 
		},
		success : function(label, element) {// error是lavel标签，element是input标签
			validSuccess(element,label);
		},
		errorPlacement : function(label, element) {
			validError(element,label);
		}
	});
	
	$("#updateContractForm").validate({
		rules : {
			startTime: {
				required: true,
				isDate: true
			},
			endTime: {
				required: true,
				isDate: true,
				isUpdateEndDateGreaterThanStartDate: true
			}
		},
		messages : {
			 
		},
		success : function(label, element) {// error是lavel标签，element是input标签
			validSuccess(element,label);
		},
		errorPlacement : function(label, element) {
			validError(element,label);
		}
	});
	 
}

function getDatas() {
	// alert(this.endTime);
	var roles;
	$.ajax({
		url : "../contractInfo/getAllContract.action",
		type : "post",
		dataType : "json",
		async : false,// 是为了内层ajax在之后访问
		success : function(data) {
			$(data).each(function() {
				this.device = getDeviceById(this.deviceId);
				this.deviceName = this.device.deviceName;
				this.customer = getCustomerById(this.customerId);
				this.customerName = this.customer.customerName;
				// 操作赋值
				this.operate = '<button class="btn btn-primary btn-xs" '
						+ 'onclick=updateContract("'+ this.id +'","'+moment(this.startTime).format('YYYY-MM-DD')+'","'+moment(this.endTime).format('YYYY-MM-DD')+'")'
						+ '>修改</button>&nbsp;'
						+ '<button class=\'btn btn-danger btn-xs\' onclick=\'singleDelete('
						+ this.id + ')\'>删除</button>';
			});
			roles = data;
		},
		error : function() {
			toastr.error("获取合同信息出错，请联系管理员");
		}
	});
	return roles;
}

// 新增合同
function addContract() {
	formReset("#addContractForm");
	addContractFormInit();
	$("#addContractModal").modal("show");
}

function addContractFormInit() {
	$.ajax({
		url: "../customer/getAllcustomer.action",
		type: "post",
		async: false,
		success: function(data) {
			var array = [];
			for(var i=0;i<data.length;i++){
			     var temp = {"id":data[i].id, 'word':data[i].customerName};
			     array.push(temp);
			}
			
			$("#customerId").bsSuggest("destroy");
			
			var bsSuggestAreaHtml = '<div class="input-group">'
							      +     '<input type="text" placeholder="支持模糊搜索" class="form-control" id="customerId" name="suggestCustomerId" >'
							      +     '<input type="hidden" name="customerId" value="-1"/>'
							      +     '<div class="input-group-btn" id="suggestDiv">'
							      +         '<button type="button" class="btn btn-white dropdown-toggle" data-toggle="dropdown">'
							      +             '<span class="caret"></span>'
							      +         '</button>'
							      +         '<ul class="dropdown-menu dropdown-menu-right my-treetable-hover z-index-5000" role="menu">'
							      +         '</ul>'
							      +     '</div>'
							      +  '</div>';
			$("#customerIdSuggestArea").html(bsSuggestAreaHtml);
			
			$("#customerId").bsSuggest({
				indexId: 0, 
				indexKey: 1, //data.value 的第几个数据，作为input输入框的显示内容
				data: {'value': array}
			}).on('onSetSelectValue', function (e, keyword) {  
				isBsSuggestCustomerIdSelected = true;
				$("#addContractForm [name='customerId']").val(keyword.id);
			}).on('onUnsetSelectValue', function (e) {  
				isBsSuggestCustomerIdSelected = false;
			});  
		},
		error: function() {
			toastr.error("请求客户信息发生错误，请联系管理员")
		}
	});
	$.ajax({
		url: "../device/query.action",
		type: "post",
		async: false,
		data: {"deviceStatus":"1"},
		success: function(data) {
			var array = [];
			for(var i=0;i<data.length;i++){
			     var temp = {"id":data[i].id, 'word':data[i].deviceName};
			     array.push(temp);
			}
			
			$("#deviceId").bsSuggest("destroy");
			
			var bsSuggestAreaHtml = '<div class="input-group">'
							      +     '<input type="text" placeholder="支持模糊搜索" class="form-control" id="deviceId" name="suggestDeviceId" >'
							      +     '<input type="hidden" name="deviceId" value="-1"/>'
							      +     '<div class="input-group-btn" id="suggestDiv">'
							      +         '<button type="button" class="btn btn-white dropdown-toggle" data-toggle="dropdown">'
							      +             '<span class="caret"></span>'
							      +         '</button>'
							      +         '<ul class="dropdown-menu dropdown-menu-right my-treetable-hover z-index-5000" role="menu">'
							      +         '</ul>'
							      +     '</div>'
							      +  '</div>';
			$("#deviceIdSuggestArea").html(bsSuggestAreaHtml);
			
			$("#deviceId").bsSuggest({
				indexId: 0, 
				indexKey: 1, //data.value 的第几个数据，作为input输入框的显示内容
				data: {'value': array}
			}).on('onSetSelectValue', function (e, keyword) {  
				isBsSuggestDeviceIdSelected = true;
				$("#addContractForm [name='deviceId']").val(keyword.id);
			}).on('onUnsetSelectValue', function (e) {  
				isBsSuggestDeviceIdSelected = false;
			});  
		},
		error: function() {
			toastr.error("请求设备信息发生错误，请联系管理员")
		}
	});
	
}

// 保存
function addContractSave() {
	if (!$("#addContractForm").valid()) {
		return false;
	}
	var datas = $("#addContractForm").serialize();
	$.ajax({
		url : "../contractInfo/save.action",
		type : "post",
		data : datas,
		success : function(data) {
			if (data.success == "true") {
				toastr.success("保存成功");
				$("#contractTable").bootstrapTable("load", getDatas());
			}
		},
		error : function() {
			toastr.error("提交到数据库发生错误，请联系管理员");
		}
	});
	$("#addContractModal").modal("hide");
}


function showContractDetail(contract) {
	var contractDetailHtml = '<p style="text-align: center; color: #6294AD;"><b>基本信息</b></p>'
		+	'<p>id：' + contract.id + '</p>'
		+	'<p>客户姓名：' + contract.customerName + '</p>'
		+	'<p>设备名称：' + contract.deviceName + '</p>'
		+	'<p>保修时间：' + getFormatTime(contract.startTime,"YYYY-MM-DD") + ' 到 ' + getFormatTime(contract.endTime,"YYYY-MM-DD") + '</p>'
		+	'<p>创建人：' + getUserNameById(contract.createUserId) + '</p>'
		+	'<p>创建时间：' + getDefaultTime(contract.createTime) + '</p>';
	
	contractDetailHtml	+='<hr/><p style="text-align: center; color: #6294AD;"><b>客户信息</b></p>'
		+	'<p>id：' + contract.customer.id + '</p>'
		+	'<p>用户名：' + contract.customer.loginName + '</p>'
		+	'<p>密码：' + contract.customer.customerPassword + '</p>'
		+	'<p>姓名：' + contract.customer.customerName + '</p>'
		+	'<p>创建人：' + getUserNameById(contract.customer.createUserId) + '</p>'
		+	'<p>创建时间：' + getDefaultTime(contract.customer.createTime) + '</p>';
		

	contractDetailHtml += '<p style="text-align: center; color: #6294AD;"><b>设备信息</b></p>'
		+	'<p>id：' + contract.device.id + '</p>'
		+	'<p>设备名称：' + contract.device.deviceName + '</p>'
	
	$.ajax({
		url:"../deviceAttr/query.action",
		type: "post",
		data: {"deviceId":contract.device.id, "attrStatus":"1"},
		async: false,
		success: function(data) {
			$(data).each(function(){
				contractDetailHtml += '<p>'+getAttrNameName(this.attrNameId)+'：'+this.attrValue+'</p>';
			});
		}
	});
		
	contractDetailHtml += '<p>售后服务号：' + contract.device.deviceServiceNumber + '</p>'
		+	'<p>设备描述：<pre style="white-space: pre-wrap !important;word-wrap: break-word !important;">' + contract.device.deviceDesc + '</pre></p>'
		+	'<p>设备图片：<div class="detailImageDiv"><img style="display:block; margin:0 auto;" src="' + contract.device.deviceImageUrl + '"/><div></p>'
		+	'<p>创建人：' + getUserNameById(contract.device.createUserId) + '</p>'
		+	'<p>创建时间：' + getDefaultTime(contract.device.createTime) + '</p>';
			

	$("#contractDetailShow").html(contractDetailHtml);
	$("#contractDetailModal").modal("show");
}


//修改
function updateContract(id, startTime, endTime) {

	formReset("#updateContractForm");
	$("#updateContractForm [name='id']").val(id);
	
	 
	$("#updateContractForm [name='startTime']").val(startTime);
	$("#updateContractForm [name='endTime']").val(endTime);
	
	$("#updateContractModal [onclick='updateContractSave()']").attr("disabled", "disabled");
	
	$("#updateContractForm input,textarea").bind('change', function(){
		$("#updateContractModal [onclick='updateContractSave()']").removeAttr("disabled");
	});
		 
	$("#updateContractModal").modal("show");
}

//修改保存
function updateContractSave() {
	if (!$("#updateContractForm").valid()) {
		return false;
	}
	// alert($("#updatecontracteId").val());
	var contract = $("#updateContractForm").serialize();
	console.log(contract);
	$.ajax({
		url : "../contractInfo/update.action",
		type : "post",
		data : contract,
		success : function(data) {
			if (data.success == "true") {
				toastr.success("更新成功");
				$("#contractTable").bootstrapTable("load", getDatas());
			}
		},
		error : function() {
			toastr.error("提交请求发生错误，请联系管理员");
		}
	});
	$("#updateContractModal").modal("hide");
}
 

// 批量删除
function batchDelete() {
	var selectedRoles = $("#contractTable").bootstrapTable('getSelections');
	// console.log(JSON.stringify(selectedRoles)); //Array[Object, Object, ...]
	// return;
	if (selectedRoles.length == 0) {
		toastr.error("请勾选你要删除的数据");
		return false;
	}
	var roleIds = new Array();
	$(selectedRoles).each(function(index, role) {
		roleIds[index] = role.id;
	})

	deleteCore(roleIds);

}

function singleDelete(id) {
	var contractIds = new Array();
	contractIds[0] = id;
	deleteCore(contractIds);
}

function deleteCore(contractIds) {
	swal({
		title : "您确定要删除所选信息吗",
		text : "删除后将无法恢复，请谨慎操作！",
		type : "warning",
		showCancelButton : true,
		confirmButtonColor : "#DD6B55",
		confirmButtonText : "删除",
		closeOnConfirm : false
	}, function() {
		$.ajax({
			url : "contract/batchDelete.action",
			type : "post",
			data : {
				"contractIds" : contractIds
			},
			success : function(data) {
				if (data.success == "true") {
					swal("删除成功", "您已经永久删除了所选信息。", "success");
					$("#contractTable").bootstrapTable("load", getDatas());
				} else {
					swal("删除失败", "后台处理发生错误，请联系管理员", "error");
				}
			},
			error : function() {
				swal("操作失败", "提交请求错误，请联系管理员。", "error");
			}
		});
	});
}

